package com.icbc.cc.security.app;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.icbc.cte.logging.Log;
import com.icbc.cte.logging.LogFactory;
import com.icbc.ctp.ioc.xmlconfig.FileSystemXmlApplicationContext;
import com.icbc.ctp.jdbc.JDBCTemplate;
import com.icbc.ctp.jdbc.core.ConnectionCallback;
import com.icbc.ctp.jdbc.exception.SQLAccessException;

public class LogUtil {
	
	public static Log log = LogFactory.getCtpLog(LogUtil.class);

	public static void recordApiLog(final String url, final String bizid, final String request, final String response) {
		
		try {
			JDBCTemplate jdbcTemplate = (JDBCTemplate) FileSystemXmlApplicationContext.get("jdbcTemplate");

			jdbcTemplate.execute(new ConnectionCallback<String>() {

				@Override
				public String doInConnection(Connection conn)
						throws SQLException, SQLAccessException {

					conn.setAutoCommit(false);
					String sql = "insert into http_log (url, bizid, request, response1, response2) values (?, ?, ?, ?, ?)";
					
					PreparedStatement stmt = null;
					try {
						stmt = conn.prepareStatement(sql);
						
						stmt.setString(1, url);
						stmt.setString(2, bizid);
						stmt.setString(3, request);
						if (response.length() > 3800) {
							stmt.setString(4, response.substring(1, 3800));
							if (response.substring(3801).length() > 3800) {
								stmt.setString(5, response.substring(3801, 3801 + 3800));
							}
						} else {
							stmt.setString(4, response);
							stmt.setString(5, "");
						}

						stmt.execute();
						
						conn.commit();
						
						
					} catch (Exception e) {
						log.error(e);
					} finally {
						if (stmt != null) {
							stmt.close();
						}
					}

					return "0";
				}
			});
			
		} catch (Exception e) {
			log.error(e);
		}
	}
}
